﻿using System;
using System.Configuration;
using System.Reflection;

namespace CodePlex.TfsPluginSuite.Configuration
{
    /// <summary>
    /// Configuration Manager for the custom TFSPluginSuite section
    /// </summary>
    public static class TfsPluginSuiteConfigurationManager
    {
        private static Assembly configurationDefiningAssembly;

        static TfsPluginSuiteConfigurationManager()
        {
            string strPluginFile = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            configurationDefiningAssembly = Assembly.LoadFrom(strPluginFile);
            var exeFileMap = new ExeConfigurationFileMap();
            exeFileMap.ExeConfigFilename = string.Format("{0}.config", strPluginFile);
            var customConfig = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);

            // This handler is needed so that the GetSection is able to retrieve the type since this dll isn't in the GAC
            AppDomain.CurrentDomain.AssemblyResolve += ConfigResolveEventHandler;
            Section = customConfig.GetSection("TfsPluginSuite") as TfsPluginSuiteConfigurationSection;
            AppDomain.CurrentDomain.AssemblyResolve -= ConfigResolveEventHandler;
        }

        public static TfsPluginSuiteConfigurationSection Section { get; private set; }

        private static Assembly ConfigResolveEventHandler(object sender, ResolveEventArgs args)
        {
            return configurationDefiningAssembly;
        }
    }
}
